package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.MarketsAccountController
import com.zxy.supplier_system.server.entity.Market
import com.zxy.supplier_system.server.entity.MarketAccount
import com.zxy.supplier_system.server.repository.MarketAccountRepository
import com.zxy.supplier_system.server.utils.orElse404
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class MarketAccountService(
    private val marketAccountRepository: MarketAccountRepository
) {
    fun getMarketAccountsByMarketId(marketId: Int): List<MarketsAccountController.MarketAccountResponse> {
        return marketAccountRepository.findAllByMarket_Id(marketId).map { MarketsAccountController.MarketAccountResponse(it.name,it.id!!) }
    }

    @Transactional
    fun createMarketAccount(marketId: Int, request: MarketsAccountController.CreateMarketAccountRequest):MarketAccount {
        return marketAccountRepository.save(MarketAccount().apply {
            this.name = request.name
            this.market = Market().apply {
                this.id = marketId
            }
        })
    }


    @Transactional
    fun updateMarketAccount(
        marketId: Int,
        request: MarketsAccountController.CreateMarketAccountRequest,
        id: Int
    ): MarketAccount {
        val marketAccount = this.marketAccountRepository.findByIdOrNull(id).orElse404()
        marketAccount.name = request.name
        return  this.marketAccountRepository.save(marketAccount)
    }

    @Transactional
    fun deleteMarketAccount(marketId: Int, id: Int) {
        return this.marketAccountRepository.deleteByMarket_IdAndId(marketId,id)
    }

}
